import json
from aiohttp import web
from utils.ResponseUtils import toResponse
from utils import ConstValues

def json_error(code,message,data):
    return web.Response(
        body=json.dumps({'code':code,'message': message,'data':data}).encode('utf-8'),
        content_type='application/json')



@web.middleware
async def error_middleware(request, handler):
    try:
        response = await handler(request)
        if response.status != 200:
            return json_error(response.status,response.message,response.body)
        return response
    except web.HTTPException as ex:
        if ex.status != 200:
            return json_error(ex.status,ex.reason,{})
        raise




